import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../services/device/connectivity_service.dart';

/// 连接控制器
/// 负责管理应用网络连接状态
class ConnectivityController extends GetxController {
  // 单例访问器
  static ConnectivityController get to => Get.find();
  
  // 注入服务
  final ConnectivityService _connectivityService = Get.find<ConnectivityService>();
  
  // 当前连接状态
  final RxBool _isConnected = false.obs;
  bool get isConnected => _isConnected.value;
  
  // 当前连接类型
  final Rx<String> _connectionType = 'none'.obs;
  String get connectionType => _connectionType.value;
  
  // 订阅连接变化
  StreamSubscription? _connectivitySubscription;
  
  @override
  void onInit() {
    super.onInit();
    
    // 初始化连接状态
    _initConnectivity();
    
    // 监听连接变化
    _connectivitySubscription = _connectivityService.onConnectivityChanged
        .listen(_updateConnectionStatus);
  }
  
  @override
  void onClose() {
    _connectivitySubscription?.cancel();
    super.onClose();
  }
  
  /// 初始化连接状态
  Future<void> _initConnectivity() async {
    try {
      final status = await _connectivityService.checkConnectivity();
      _updateConnectionStatus(status);
    } catch (e) {
      debugPrint('检查连接状态时出错: $e');
      _isConnected.value = false;
      _connectionType.value = 'none';
    }
  }
  
  /// 更新连接状态
  void _updateConnectionStatus(String status) {
    _connectionType.value = status;
    _isConnected.value = status != 'none';
    
    // 如果网络状态变化，可以在此处显示提示
    if (!_isConnected.value) {
      _showOfflineSnackbar();
    } else if (status == 'wifi' || status == 'mobile') {
      // 如果之前断开后重新连接，可以显示已重新连接的提示
      _showOnlineSnackbar();
    }
    
    debugPrint('网络连接状态: $status');
  }
  
  /// 显示断网提示
  void _showOfflineSnackbar() {
    if (Get.isSnackbarOpen) {
      Get.closeAllSnackbars();
    }
    
    Get.snackbar(
      '网络断开',
      '请检查网络连接',
      icon: const Icon(Icons.signal_wifi_off, color: Colors.white),
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }
  
  /// 显示恢复连接提示
  void _showOnlineSnackbar() {
    if (Get.isSnackbarOpen) {
      Get.closeAllSnackbars();
    }
    
    Get.snackbar(
      '网络已连接',
      '网络连接已恢复',
      icon: const Icon(Icons.wifi, color: Colors.white),
      snackPosition: SnackPosition.BOTTOM,
      backgroundColor: Colors.green,
      colorText: Colors.white,
      duration: const Duration(seconds: 2),
    );
  }
  
  /// 手动检查网络连接
  Future<void> checkConnectivity() async {
    final status = await _connectivityService.checkConnectivity();
    _updateConnectionStatus(status);
    return;
  }
} 